import { Button, Table,Tag ,Spin,Modal, Popconfirm, Input, Tooltip, Select, Row } from 'antd';
import type { TableProps } from 'antd';
import "./index.less"
import { useEffect, useState } from 'react';
import { get, post } from '@/api';
export default function AuthorityManage(){
  const [userDataList,setUserDataList] = useState([] as DataType[])
  const [curArtId,setCurArtId] = useState<number>(0)
  const [isSpin,setIsSpin] = useState(false)
  const [isOpen,setIsOpen] = useState(false)

  const [previewUrl,setPreviewUrl] = useState('')
  const [filterObj,setFilterObj] = useState<{name:string,role:any[]}>({
    name:'',
    role:[]
  })
  const [filterTimer,setFilterTimer] = useState<number>(0)
  const filterTitle = {
    name:'用户名',
    role:'权限'
  }
  interface DataType {
    id: number;
    name: string;
    avatar: string;
    email: string;
    role: string[];
    isFromOauth:boolean;
    is_admin:boolean;
    isOpenPopConfirm:boolean
  }

  type filterTitleType = 'name' | 'role'
  const columns:TableProps<DataType>['columns'] = [
    {
      width:200,
      title: filterHeader('name'),
      dataIndex: 'name',
      key: 'name'
    },
    {
      width:200,
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
      render:(email)=>(
        <span>{ email || '-' }</span>
      )
    },
    {
      width:200,
      title: '头像',
      dataIndex: 'avatar',
      key: 'avatar',
      render:(_,{isFromOauth,avatar})=>{
        return (
          <>
            <img className='avatar' src={isFromOauth ? avatar : process.env.REACT_APP_BASE_URL + avatar} alt="" onClick={()=>preViewImage(isFromOauth ? avatar : process.env.REACT_APP_BASE_URL + avatar)}/>
          </>
        )
      }
    },
    {
      width:200,
      title: filterHeader('role'),
      key: 'role',
      dataIndex: 'role',
      render:(_,{is_admin,role})=>(
        <>
          {
            role.map((item,index)=>(
              <Tooltip title={tipByRole(item)}>
                <Tag key={index} color={item === '管理员' ? 'cyan' : 'geekblue'}>{item}</Tag>
              </Tooltip>
            ))
          }
        </>
      )
    },
    {
      width:220,
      title: '操作',
      key: 'actions',
      render:(_,{is_admin,id,isOpenPopConfirm,name})=>(
        <Popconfirm
          title={is_admin ? '撤销管理员' : '设为管理员'}
          description={is_admin ? `确定撤销${name}的管理员身份?` : `确定设置${name}为管理员?`}
          open={isOpenPopConfirm}
          cancelText='取消'
          okText='确认'
          onConfirm={()=>changeManagerRole(curArtId,!is_admin)}
          onCancel={()=>handlePopConfirmHide(id)}
        >
          {
            is_admin ?
              <Button type='link' onClick={()=>openPopConfirm(id)}>撤销管理员</Button> :
              <Button type='link' onClick={()=>openPopConfirm(id)}>设为管理员</Button>
          }
        </Popconfirm>
      )
    },
  ];

  // 过滤查询
  useEffect(()=>{
    if(filterTimer){
      clearTimeout(filterTimer)
    }
    let timer:number = window.setTimeout(()=>{
      getTableByFilter()
    },500)
    setFilterTimer(timer)
  },[filterObj])
  // 渲染钩子
  useEffect(()=>{
    getUserDataPage()
  },[])
  // 角色提示
  const tipByRole = (role:string)=>{
    return role === '管理员' ? '博客的管理员，可审核文章及后台管理端等权限' : '博客普通用户，可发表文章及评论'
  }
  // 过滤表头
  function filterHeader(title:filterTitleType){
    let filterHeaderComp
    // 权限下拉选项
    const roleOptions = [
      {
        value:false,
        label:'普通用户'
      },
      {
        value:true,
        label:'管理员'
      }
    ]
    const changeRoleFilter = (val:any[])=>{
      setFilterObj({
        ...filterObj,
        role:val
      })
    }
    switch(title){
      case 'name':
        filterHeaderComp = (
          <>
            <span>{filterTitle[title] || '-'}</span>
            <Input className='input-user' allowClear={true} value={filterObj.name} placeholder='请输入用户名' onChange={(e)=>{ setFilterObj({...filterObj,name:e.target.value as string}) }}></Input>
          </>
        )
        break;
      case 'role':
        filterHeaderComp = (
          <>
            <div>{filterTitle[title] || '-'}</div>
            <Select mode="multiple" className='select-role' value={filterObj.role} options={roleOptions} allowClear  placeholder='请选择权限' onChange={changeRoleFilter}></Select>
          </>
        )
        break;
      default:
        break       
    }
    return filterHeaderComp
  }
  
  const getTableByFilter = ()=>{
    let emptyFlag = true
    Object.keys(filterObj).forEach(item=>{
      if(filterObj[item as filterTitleType]){
        emptyFlag = false
      }
    })
    // 调接口搜索
    getUserDataPage(emptyFlag)
  }
  // 获取用户信息的列表
  const getUserDataPage = async (filterEmpty:Boolean = true)=>{
    try {
      setIsSpin(true)
      const param = Object.fromEntries(Object.entries(filterObj).filter(item=> item[1] && item[1].length)) 
      const res = filterEmpty ? await post('/manage/getUserDataList') : await post('/manage/getUserDataList',param)
      res.data = res.data.map((item:any)=>{
        return {...item,isOpenPopConfirm:false}
      })
      setUserDataList([
        ...res.data
      ])
    } catch(e){
      console.log(e)
    } finally {
      setIsSpin(false)
    }
    
  }
  // 变更管理员身份事件
  const changeManagerRole = async (id:number,flag:boolean)=>{
    try {
      const res = await post('/manage/changeManagerRole',{id,flag})
      if(res.code === 200){
        await getUserDataPage()
      }
    } catch(e){
      console.log(e)
    }
    
  }
  // 变量
  const imgPreviewModalStyles = {
    body:{
      minWidth:500,
      display:'flex'
    }
  }
  // 预览文章配图
  const preViewImage = (url:string)=>{
    setPreviewUrl(url)
    setIsOpen(true)
  }
  // 撤销与设置气泡确认框
  const openPopConfirm = (id:number)=>{
    setCurArtId(id)
    // 先关闭所有的popConfirm
    setUserDataList(userDataList.map(item=>{
      if(item.isOpenPopConfirm) item.isOpenPopConfirm = false
      if(item.id === id){
        item.isOpenPopConfirm = true
      }
      return item
    }))
  }
  // 关闭气泡框
  const handlePopConfirmHide = (id:number)=>{
    setUserDataList(userDataList.map(item=>{
      if(item.id === id){
        item.isOpenPopConfirm = false
      }
      return item
    }))
  }
  
  return (
    <>
      <Spin tip={'加载中'} spinning={isSpin}>
      <Table pagination={false} rowKey={(row:any)=>row.id} columns={columns} dataSource={userDataList} scroll={{y:'calc(100vh - 152px)'}}/>
      </Spin>
      <Modal styles={imgPreviewModalStyles} open={isOpen} width={700} maskClosable={true} closable={false} footer={null} onCancel={()=>setIsOpen(false)}>
        <img style={{width:'97%',height:'500px',margin:'0 auto'}} src={previewUrl} alt="" />
      </Modal>
    </>
    
  )
}